import gradio as gr
import requests
import io


# 定义一个函数，用于录制音频并上传到服务端
import requests


def upload_audio(audio_file):
    url = "http://localhost:5000/upload"  # 确保使用正确的协议
    files = {'file': ('audio.wav', audio_file, 'audio/wav')}
    # 如果 audio_file 是一个文件对象，确保在发送前重置文件指针
    if hasattr(audio_file, 'seek'):
        audio_file.seek(0)
    response = requests.post(url, files=files)
    if response.status_code == 200:
        return "Audio uploaded successfully!"
    else:
        # 可以打印或记录更多错误信息
        print("Error:", response.status_code, response.text)
        return "Failed to upload audio."

    # 定义一个Gradio界面


with gr.Blocks() as demo:
    with gr.Row():
        audio_input = gr.Audio(label="Record Audio")
        upload_button = gr.Button("Upload Audio")

    with gr.Row():
        result = gr.Textbox(label="Result")

    upload_button.click(fn=upload_audio, inputs=audio_input, outputs=result)

# 启动Gradio应用
demo.launch(debug=True)